import { create } from 'zustand';

const initialOrders = [
  {
    id: '1',
    orderNumber: 'ORD20240315001',
    memberId: '1',
    memberName: '张三',
    memberPhone: '13800138001',
    tableNumber: 'A01',
    items: [
      { dishName: 'IPA精酿啤酒', size: '500ml', quantity: 2, price: 45, discount: 90 },
      { dishName: '世涛黑啤', size: '330ml', quantity: 2, price: 28, discount: 100 }
    ],
    originalAmount: 176.00,
    discount: 90,
    amount: 158.50,
    status: 'completed',
    orderTime: '2024-03-15 14:30:00',
    completedTime: '2024-03-15 15:00:00',
    createdAt: '2024-03-15 14:30:00',
    updatedAt: '2024-03-15 14:30:00'
  },
  {
    id: '2',
    orderNumber: 'ORD20240316002',
    memberId: '2',
    memberName: '李四',
    memberPhone: '13800138002',
    tableNumber: 'B05',
    items: [
      { dishName: '小麦白啤', size: '500ml', quantity: 1, price: 38, discount: 100 },
      { dishName: '果香拉格', size: '330ml', quantity: 2, price: 20, discount: 100 }
    ],
    originalAmount: 78.00,
    discount: 100,
    amount: 78.00,
    status: 'pending',
    orderTime: '2024-03-16 10:20:00',
    completedTime: null,
    createdAt: '2024-03-16 10:20:00',
    updatedAt: '2024-03-16 10:20:00'
  },
  {
    id: '3',
    orderNumber: 'ORD20240317003',
    memberId: '3',
    memberName: '王五',
    memberPhone: '13800138003',
    tableNumber: 'C12',
    items: [
      { dishName: '比利时修道院啤酒', size: '500ml', quantity: 3, price: 60, discount: 85 },
      { dishName: 'IPA精酿啤酒', size: '330ml', quantity: 4, price: 25, discount: 100 }
    ],
    originalAmount: 280.00,
    discount: 85,
    amount: 238.00,
    status: 'completed',
    orderTime: '2024-03-17 16:45:00',
    completedTime: '2024-03-17 17:30:00',
    createdAt: '2024-03-17 16:45:00',
    updatedAt: '2024-03-17 16:45:00'
  },
  {
    id: '4',
    orderNumber: 'ORD20240318004',
    memberId: '4',
    memberName: '赵六',
    memberPhone: '13800138004',
    tableNumber: 'A03',
    amount: 25.50,
    status: 'cancelled',
    orderTime: '2024-03-18 09:15:00',
    completedTime: null,
    createdAt: '2024-03-18 09:15:00',
    updatedAt: '2024-03-18 09:15:00'
  },
  {
    id: '5',
    orderNumber: 'ORD20240319005',
    memberId: '5',
    memberName: '钱七',
    memberPhone: '13800138005',
    tableNumber: 'B08',
    amount: 198.00,
    status: 'completed',
    orderTime: '2024-03-19 15:30:00',
    completedTime: '2024-03-19 16:15:00',
    createdAt: '2024-03-19 15:30:00',
    updatedAt: '2024-03-19 15:30:00'
  },
  {
    id: '6',
    orderNumber: 'ORD20240320006',
    memberId: '6',
    memberName: '孙八',
    memberPhone: '13800138006',
    tableNumber: 'A07',
    amount: 56.00,
    status: 'pending',
    orderTime: '2024-03-20 11:00:00',
    completedTime: null,
    createdAt: '2024-03-20 11:00:00',
    updatedAt: '2024-03-20 11:00:00'
  },
  {
    id: '7',
    orderNumber: 'ORD20240321007',
    memberId: '1',
    memberName: '张三',
    memberPhone: '13800138001',
    tableNumber: 'C03',
    amount: 268.00,
    status: 'completed',
    orderTime: '2024-03-21 13:20:00',
    completedTime: '2024-03-21 14:10:00',
    createdAt: '2024-03-21 13:20:00',
    updatedAt: '2024-03-21 13:20:00'
  },
  {
    id: '8',
    orderNumber: 'ORD20240322008',
    memberId: '3',
    memberName: '王五',
    memberPhone: '13800138003',
    tableNumber: 'B02',
    amount: 125.50,
    status: 'cancelled',
    orderTime: '2024-03-22 17:40:00',
    completedTime: null,
    createdAt: '2024-03-22 17:40:00',
    updatedAt: '2024-03-22 17:40:00'
  }
];

const useOrdersStore = create((set, get) => ({
  allOrders: initialOrders,
  orders: initialOrders,
  loading: false,
  error: null,
  filters: {
    status: 'all'
  },

  getOrders: async (filters = {}) => {
    set({ loading: true });
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const { allOrders } = get();
      let filteredOrders = [...allOrders];
      
      if (filters.status && filters.status !== 'all') {
        filteredOrders = filteredOrders.filter(
          order => order.status === filters.status
        );
      }

      if (filters.orderNumber) {
        filteredOrders = filteredOrders.filter(
          order => order.orderNumber.includes(filters.orderNumber)
        );
      }

      if (filters.memberId) {
        filteredOrders = filteredOrders.filter(
          order => order.memberId === filters.memberId || order.memberPhone.includes(filters.memberId)
        );
      }

      if (filters.dateRange && filters.dateRange.length === 2) {
        const [startDate, endDate] = filters.dateRange;
        filteredOrders = filteredOrders.filter(order => {
          const orderDate = new Date(order.orderTime);
          return orderDate >= new Date(startDate) && orderDate <= new Date(endDate);
        });
      }
      
      set({ 
        orders: filteredOrders, 
        loading: false,
        filters 
      });
    } catch (error) {
      set({ error: error.message, loading: false });
    }
  },

  getOrderById: (id) => {
    const { allOrders } = useOrdersStore.getState();
    return allOrders.find(order => order.id === id);
  },

  updateOrder: async (id, updates) => {
    set({ loading: true });
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      
      set((state) => {
        const updatedAllOrders = state.allOrders.map(order =>
          order.id === id
            ? { ...order, ...updates, updatedAt: new Date().toISOString() }
            : order
        );
        
        return {
          allOrders: updatedAllOrders,
          orders: updatedAllOrders,
          loading: false
        };
      });
      
      const { filters } = get();
      await get().getOrders(filters);
    } catch (error) {
      set({ error: error.message, loading: false });
      throw error;
    }
  },

  deleteOrder: async (id) => {
    set({ loading: true });
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      
      set((state) => ({
        allOrders: state.allOrders.filter(order => order.id !== id),
        orders: state.orders.filter(order => order.id !== id),
        loading: false
      }));
    } catch (error) {
      set({ error: error.message, loading: false });
      throw error;
    }
  },

  updateOrderStatus: async (id, status) => {
    set({ loading: true });
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      
      set((state) => {
        const updatedAllOrders = state.allOrders.map(order =>
          order.id === id
            ? { ...order, status, updatedAt: new Date().toISOString() }
            : order
        );
        
        return {
          allOrders: updatedAllOrders,
          orders: updatedAllOrders,
          loading: false
        };
      });
      
      const { filters } = get();
      await get().getOrders(filters);
    } catch (error) {
      set({ error: error.message, loading: false });
      throw error;
    }
  },

  setFilters: (filters) => {
    set({ filters });
  },

  clearError: () => set({ error: null })
}));

export default useOrdersStore;
